package com.example.dbmeta.meta.common.xml;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.example.dbmeta.exception.DbMetaBootException;
import com.example.dbmeta.exception.DbMetaErrorCode;
import com.example.dbmeta.meta.common.xml.DataInstance;

public class ConfigValidator {

    /**
     * 验证数据源实例配置
     * @param dataInstances 数据源实例列表
     * @throws DbMetaBootException 如果配置无效
     */
    public static void validateDataInstances(List<DataInstance> dataInstances) {
        if (dataInstances == null || dataInstances.isEmpty()) {
            throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"至少需要配置一个数据源实例");
        }

        Set<String> instanceNames = new HashSet<>();

        for (DataInstance instance : dataInstances) {
            // 1. 验证实例名称存在性
            String name = instance.getDbinstancename();
            if (name == null || name.trim().isEmpty()) {
                throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"数据源实例必须包含有效的 dbinstancename");
            }

            // 2. 检查实例名称唯一性
            if (instanceNames.contains(name)) {
                throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"发现重复的数据源实例名称: " + name);
            }
            instanceNames.add(name);

            // 3. 验证其他必要属性
            if (instance.getUrl() == null || instance.getUrl().isEmpty()) {
                throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,name + ": URL不能为空");
            }

            if (instance.getDriverclassname() == null || instance.getDriverclassname().isEmpty()) {
                throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,name + ": 驱动类名不能为空");
            }
        }
    }

    /**
     * 验证目标数据源配置
     * @param destDataSource 目标数据源
     * @throws DbMetaBootException 如果配置无效
     */
    public static void validateDestination(DestinationDataSource destDataSource) {
        if (destDataSource == null) {
            throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"必须配置目标数据源");
        }

        if (destDataSource.getUrl() == null || destDataSource.getUrl().isEmpty()) {
            throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"目标数据源URL不能为空");
        }

        if (destDataSource.getDriverclassname() == null || destDataSource.getDriverclassname().isEmpty()) {
            throw new DbMetaBootException(DbMetaErrorCode.CONFIG_PARSE_ERROR,"目标数据源驱动类名不能为空");
        }
    }
}
